<template>
  <TableView class="table">
    <template #form>
      <NSpace justify="space-between" align="center">
        <NSpace align="center">
          项目名称:
          <NInput style="width: 280rem" placeholder="请输入项目名称" clearable v-model:value="paginationReactive.projectName" />
          <NButton type="primary" style="width: 78rem" ghost
            @click="() => ((paginationReactive.page = 1), getLaborList())">
            查询
          </NButton>
        </NSpace>
        <NButton type="primary" style="width: 115rem" @click="$router.push({ path: '/OA/Labor/LaborAdd' })">
          劳务申请
        </NButton>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable v-bind="props" :bordered="false" :columns="columns" :data="tableData" :pagination="false"
        :loading="tableLoading" />
    </template>

    <template #pagination>
      <NPagination :page-sizes="paginationReactive.pageSizes" :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page" :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange" @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker show-quick-jumper :suffix="() => '页'">
        <template #prefix>
          <span style="font-size: 14px;"> 共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal :auto-focus="false" v-model:show="modalVisible" @close="modalVisible = false">
    <VDialogContent @close="modalVisible = false" @submit="recall" title="撤回提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定撤回该条加班申请吗？
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import {
  NSpace,
  NButton,
  NDataTable,
  NPagination,
  useMessage,
  NModal,
  NInput
} from 'naive-ui'
import { h, reactive, ref, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import type { OverTimeModel } from '@/api/overTime'
import type { HttpResponse } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import router from '@/router'
import { useViewerStore } from '@/views/OA/Common/store'
import { RecordType } from '@/router/utils'

const useStore = useViewerStore()
const message = useMessage()
const route = useRoute()
const modalVisible = ref(false)

const columns: any = [
  {
    title: '申请人',
    key: 'userName',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '项目名称',
    key: 'projectName',
    width: 100,
    align: useStore.isCenter
  },
  {
    title: '项目内容',
    key: 'projectContent',
    width: 120,
    align: useStore.isCenter,
    ellipsis: {
      tooltip: {
        contentStyle: {
          maxWidth: '400rem'
        }
      }
    }
  },
  {
    title: '税前总金额',
    key: 'amount',
    width: 120,
    align: useStore.isCenter,
    // render: ({ amount }: any) => {
    //   return useStore.convertToRMB(amount)
    // }
  },
  {
    title: '总人数',
    key: 'personNum',
    width: 120,
    align: useStore.isCenter
  },
  {
    title: '申请时间',
    key: 'submitTime',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'fromStatus',
    width: 60,
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: 180,
    fixed: 'right',
    render: (row: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0553')
            router.push({ path: '/OA/Labor/LaborInfo', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      row.fromStatusCode === 'A0605' && h(
        NButton,
        {
          type: 'info',
          quaternary: true,
          loading: row.exportLoading || false,
          onClick: () => {
            singleExport(String(row.id))
          }
        },
        {
          default: () => '导出'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          style: { display: row.fromStatusCode == '审批中' ? 'inlne-block' : 'none' },
          onClick: async () => {
            recallId.value = row.id
            modalVisible.value = true
          }
        },
        {
          default: () => '撤回'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            router.push({
              path: '/OA/Labor/LaborUpdate',
              query: { id: row.id, flat: true as never }
            })
          }
        },
        {
          default: () => '再次发起'
        }
      )
    ]
  }
]
// 上一页下一页
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  projectName: null, //项目名称
  onChange: (page: number) => {
    paginationReactive.page = page
    getLaborList()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    getLaborList()
  }
})
// 撤回
const recallId = ref()
const recall = async () => {
  modalVisible.value = false
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
    module: 'receiveOrDispatch',
    api: 'dispatchRevoke',
    override: {
      data: {
        functionCode: 'A0553',
        resourceId: recallId.value
      }
    }
  })
  if (error) return message.error('撤回失败'), (tableLoading.value = false)
  if (res.code !== 0) return message.error('撤回失败'), (tableLoading.value = false)
  getLaborList()
  message.success('撤回成功')
}
const singleExport = async (id: string) => {
  tableData.value.forEach((t: any) => {
    t.exportLoading = (String(t.id) === id)
  })
  const [error, res, headers] = await sendRequest<HttpResponse>({
    module: 'labor',
    api: 'laborExport',
    override: {
      params: {
        id
      }
    }
  })
  if (error) {
    tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
    return message.error(error.message)
  }
  download(headers, res, '劳务审批单')
  message.success('导出成功')
  tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}
// 获取列表
const tableData = ref([])
const tableLoading = ref(false)
const getLaborList = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
    module: 'labor',
    api: 'laborList',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        projectName: paginationReactive.projectName
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = []
  setTimeout(() => {
    tableData.value = res.data.list.map((r: any) => {
      return {
        ...r,
        exportLoading: false
      }
    })
    paginationReactive.itemCount = res.data.totalCount
  }, 0)
}

const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,getLaborList())
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route,
  async () => {
    if (route.path == '/OA/Labor/Labor') {
      getLaborList()
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>
<style scoped lang="scss">
.table {
  padding: 29rem 30rem 42rem;
}
</style>
